<template>
  <TableView class="role">
    <template #form>
      <NSpace justify="space-between">
        <NForm
          :show-feedback="false"
          label-placement="left"
          inline
        >
          <span style="line-height: 34px">文润志愿服务联盟：</span>
          <NSelect
            :options="listOption"
            v-model:value="form.leagueId"
            placeholder="请选择联盟"
            clearable
            style="width: 150px; margin-right: 20px"
            :render-option="renderOption"
          />
          <span style="line-height: 34px">日期：</span>
         <NDatePicker input-readonly
            v-model:formatted-value="range"
            value-format="yyyy-MM-dd"
            type="daterange"
            @update:formatted-value="changeDate"
          />
          <NFormItem>
            <NButton
              type="primary"
              style="width: 78px;margin-left: 20px;"
              ghost
              @click="queryTableData(true)"
              :loading="tableLoading"
            >
              查询
            </NButton>
            <NButton
              style="width: 78px;margin: 0 15px;"
              @click="reset()"
              ghost
              type="primary"
            >
              重置
            </NButton>
            <NButton
              type="primary"
              @click="exportData()"
              :loading="exportLoading"
            >
              导出Excel
            </NButton>
          </NFormItem>
        </NForm>
      </NSpace>
    </template>
    <template #table="props">
      <n-data-table
        v-bind="props"
        :data="tableData"
        :columns="columns"
        :loading="tableLoading"
        size="small"
        :bordered="false"
        :rowKey="rowKey"
        :checked-row-keys="rowKeys"
        @update:checked-row-keys="rowKeysChange"
      />
    </template>
    <template #pagination>
      <NPagination
        show-size-picker
        show-quick-jumper
        :page-sizes="paginationReactive.pageSizes"
        :item-count="paginationReactive.itemCount"
        :page="paginationReactive.page"
        :page-size="paginationReactive.pageSize"
        @update:page="paginationReactive.onChange"
        @update:page-size="paginationReactive.onUpdatePageSize"
      >
        <template #suffix>页</template>
        <template #prefix>
          <span style="font-size: 14px">共{{ paginationReactive.itemCount }}条</span>
        </template>
      </NPagination>
    </template>
  </TableView>
</template>

<script setup lang="ts">
import {
  useMessage,
  NButton,
  NSpace,
  NDataTable,
  NInput,
  type DataTableColumns,
  NPagination,
  NModal,
  NForm,
  NFormItem,
  NSelect,
  NTag,
  NDatePicker,
  NTooltip
} from 'naive-ui'
import { onActivated, onMounted, reactive, ref, h ,watch} from 'vue'
import { sendRequest } from '@/utils/api'
import type { examineModal } from '@/api/volunteer'
import type { HttpResponse, HttpResponsePagination } from '@/utils/http'
import TableView from '@/components/TableView.vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import { useRoute, useRouter } from 'vue-router'

const message = useMessage()
const router = useRouter()

onActivated(() => {
  if (window.flags.flushRole) {
    queryTableData(true)
    window.flags.flushRole = false
  }
})

const rowKey: any = (row: any) => row.subItemId || ''
const rowKeys = ref([])
const djIds = ref([])
const tableData = ref<examineModal[]>([])
const paginationReactive = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100, 500],
  itemCount: 0,
  onChange: (page: number) => {
    paginationReactive.page = page
    queryTableData()
  },
  onUpdatePageSize: (pageSize: number) => {
    paginationReactive.pageSize = pageSize
    paginationReactive.page = 1
    queryTableData()
  }
})
const rowKeysChange = (v: any,a:any) => {
  rowKeys.value = v
  djIds.value = v
}
type Reset = () => void
function useQueryForm<T = unknown>(form: T, reset: Reset): [form: T, reset: Reset] {
  return [form, reset]
}
const reset = () => {
  resetForm();
  range.value = null
}
const modalVisible = ref(false)
const modalAdd = ref(false)
const route = useRoute()
const title = ref('志愿服务联盟新增');
const range = ref(null)
const [form, resetForm] = useQueryForm(
  reactive({
    leagueId: null,
    startDate: null,
    endDate: null
  }),
  () => {
    form.leagueId = null,
    form.startDate = null,
    form.endDate = null
  }
)

const onReset = () => {
  range.value = null
  form.leagueId = null,
  form.startDate = null,
  form.endDate = null
}

const changeDate = (v: any) => {
  range.value = v
  form.startDate = v ? `${v[0]} 00:00:00` : null
  form.endDate = v ? `${v[1]} 23:59:59`  : null
}

const rules = {
  startConfigDate: {
    required: true,
    message: '请选择签到时间',
    trigger: ['blur']
  },
  endConfigDate: {
    required: true,
    message: '请选择签出时间',
    trigger: ['blur']
  },
}

const listOption = ref([]);

const  renderOption = ({ node, option }: { node: VNode; option: SelectOption }) =>
  h(NTooltip, null, {
    trigger: () => node,
    default: () => option.label
  })

const columns: DataTableColumns<examineModal> = [
  // {
  //   type: 'selection',
  //   fixed: 'left',
  //   width: '2rem'
  // },
  {
    title: '文润志愿服务联盟',
    key: 'leagueName',
    width: '10rem',
    align: 'center'
  },
  {
    title: '出勤天数',
    key: 'attendanceDays',
    width: '10rem',
    align: 'center',
  },
  {
    title: '排班次数',
    key: 'schedulingNums',
    width: '10rem',
    align: 'center',
  },
  {
    title: '排班人数',
    key: 'peopleNums',
    width: '10rem',
    align: 'center',
  },
  {
    title: '排班时长',
    key: 'scheduleTime',
    width: '10rem',
    align: 'center',
  },
  {
    title: '出勤时间(min)',
    key: 'attendanceTime',
    width: '10rem',
    align: 'center',
  }
]
const tableLoading = ref(false)
const queryTableData = async (resetPage = false) => {
  if (resetPage) paginationReactive.page = 1
  tableLoading.value = true
  let params:any = {
    leagueId: form.leagueId,
    page: paginationReactive.page,
    limit: paginationReactive.pageSize,
  }
  if (form.startDate) {
    params.startDate = form.startDate + ' 00:00:00';
  }
  if (form.endDate) {
    params.endDate = form.endDate + ' 23:59:59';
  }

  const [error, res] = await sendRequest<HttpResponsePagination<examineModal>>({
    module: 'volunteer',
    api: 'examineList',
    override: {
      params: params
    }
  })
  tableLoading.value = false
  if (error) return message.error(error.message)
  paginationReactive.itemCount = res.data.totalCount
  tableData.value = res.data.list
}

const exportLoading = ref(false)
const exportData = async() => {
  exportLoading.value = true
  const [error, res, headers] = await sendRequest<HttpResponsePagination<any>>({
    module: 'volunteer',
    api: 'examineExport',
    override: {
      params: {
        leagueId: form.leagueId,
        startDate: form.startDate,
        endDate: form.endDate,
        page: paginationReactive.page,
        limit: 99999
      }
    }
  })
  if (error) return message.error(error.message), (exportLoading.value = false)
  download(headers, res, '志愿者考勤记录')
  exportLoading.value = false
  message.success('导出成功')
}
function download(headers: any, data: any, name?: string) {
  const val = headers['content-disposition']?.match(/(?<=filename=)(.*)/)
  let filename = val ? decodeURIComponent(val[0]) : name + '导出.xlsx'
  if (!filename.includes('xlsx')) {
    filename = filename.replace('xls', 'xlsx')
  }
  const a = document.createElement('a')
  let binaryData = []
  binaryData.push(data)
  a.href = window.URL.createObjectURL(new Blob(binaryData))
  a.download = filename
  a.click()
  window.URL.revokeObjectURL(a.href)
}

//下拉
const getFunction = async () => {
  listOption.value = []
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'volunteer',
    api: 'leagueOptions'
  })
  if (error) return message.error(error.message)
  res.data.forEach((i: any) => {
    // @ts-ignore
    listOption.value.push({ label: i.label, value: i.value })
  })
}

onMounted(() => {
  getFunction()
  queryTableData(true)
})
watch(
  () => route,
  () => {
    if (
      route.path == '/collectionManagement/collectionProcess/clueManagement/index'
    ) {
      queryTableData(true)
    }
  },
  { deep: true, immediate: true }
)
</script>

<style lang="scss" scoped>
.role {
  padding: 29rem 20rem 42rem 30rem;
  color: rgba(0, 0, 0, 0.85);
}
</style>
